1. 题目描述(简单难度)

[success] 589. N 叉树的前序遍历

2. 解法一:DFS

class Solution {
    List<Integer> resp = new ArrayList<>();
    public List<Integer> postorder(Node root) {
      if(null == root){
          return new ArrayList<>();
      }
      dfs(root);
      return resp;
    }

    public void dfs(Node root){
        if(root == null){
            return;
        }
        for(Node node : root.children){
            dfs(node);
        }
        resp.add(root.val);
    }
}
class Solution {
    List<Integer> resp = new ArrayList<>();
    public List<Integer> postorder(Node root) {
      if(null == root){
          return new ArrayList<>();
      }
      Deque<Node> deque = new LinkedList<>();
      deque.offerLast(root);
      while(!deque.isEmpty()){
         Node node = deque.pollLast();
         resp.add(node.val);
         for(Node child : node.children){
             deque.offerLast(child);
         }
      }
      Collections.reverse(resp);
      return resp;
    }
}
© gaohueric all right reserved,powered by Gitbook文件修订时间: 2021-12-08 23:22:22

results matching ""

    No results matching ""